package com.systemic.service.impl;

import com.systemic.mapper.MindfulnessMapper;
import com.systemic.mapper.MindfulnessMediaMapper;
import com.systemic.pojo.Mindfulness;
import com.systemic.pojo.MindfulnessMedia;
import com.systemic.service.MindfulnessMediaService;
import com.systemic.utils.FileUtils;
import com.systemic.vo.PageVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: MindfulnessMediaServiceImpl
 * @Description:
 * @Author:
 * @CreateTime: 2024-01-31 09:06
 * @Version:
 **/
@Service
@PropertySource("classpath:/properties/mindfulness.properties")
public class MindfulnessMediaServiceImpl implements MindfulnessMediaService {

    // 正念图片
    @Value("${mindfulness.mindfulnessMediaImgURL}")
    private String mindfulnessMediaImgURL;
    @Value("${mindfulness.mindfulnessMediaImg}")
    private String mindfulnessMediaImgPath;

    // 正念媒体
    // 视频格式
    @Value("${mindfulness.mindfulnessMediaURL}")
    private String mindfulnessMediaURL;
    @Value("${mindfulness.mindfulnessMedia}")
    private String mindfulnessMediaPath;
    // 音频格式
    @Value("${mindfulness.mindfulnessAudioURL}")
    private String mindfulnessAudioURL;

    @Resource
    private MindfulnessMediaMapper mindfulnessMediaMapper;

    @Resource
    private MindfulnessMapper mindfulnessMapper;

    /**
     * 新增
     *
     * @param image
     * @param media
     * @param mindfulnessMedia
     * @param mediaClass
     * @return
     */
    @Override
    @Transactional
    public int add(MultipartFile image, MultipartFile media,
                   MindfulnessMedia mindfulnessMedia, Integer[] mediaClass) {
        int row = 0;
        if (!media.isEmpty()){
            Date date = new Date();
            String mediaURL = "";
            // 上传正念媒体文件
            if (FileUtils.isMusic(media)){
                mediaURL = FileUtils.uploadImage(media,mindfulnessMediaPath,mindfulnessAudioURL);
            } else if (FileUtils.isVideo((media))){
                mediaURL = FileUtils.uploadImage(media,mindfulnessMediaPath,mindfulnessMediaURL);
            }
            if (!mediaURL.equals("")){
                mindfulnessMedia.setMediaUrl(mediaURL);
            } else {
                return 0;
            }

            if(!image.isEmpty()){
                String ImgURL = FileUtils.uploadImage(image,mindfulnessMediaImgPath,mindfulnessMediaImgURL);
                mindfulnessMedia.setImgUrl(ImgURL);
            }
            mindfulnessMedia.setGmtCreate(date);
            mindfulnessMedia.setGmtModified(date);
            row = mindfulnessMediaMapper.insert(mindfulnessMedia) + row;
            Integer mediaId = mindfulnessMediaMapper.getLastInsertId();  // 获取自增主键
            // 如果存储正念类别的数组不为空
            if (mediaClass.length!=0){
                for (Integer classId:mediaClass) {
                    Mindfulness mindfulness = new Mindfulness(null,classId,mediaId);
                    row = mindfulnessMapper.insert(mindfulness)+row;   // 新增正念类别实体关系
                }
            }
        }
        return row;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public int delete(Integer id) {
        int row = 0;
        MindfulnessMedia mindfulnessMedia = mindfulnessMediaMapper.selectById(id);
        if (mindfulnessMedia!=null){
            Mindfulness mindfulness = new Mindfulness();
            mindfulness.setId(id);
            List<Mindfulness>  mindfulnessList = mindfulnessMapper.select(mindfulness);
            // 删除实体关系
            if (!mindfulnessList.isEmpty()){
                for (Mindfulness res:mindfulnessList) {
                    row = mindfulnessMapper.delete(res)+row;
                }
            }
            // 删除图片和正念媒体
            try{
                String img = mindfulnessMedia.getImgUrl();
                if (img!=null){
                    URL imgUrl = new URL(img);
                    String imgFileName = imgUrl.getPath().substring(imgUrl.getPath().lastIndexOf("/") + 1);
                    FileUtils.delete(mindfulnessMediaImgPath + imgFileName);
                }
                String media = mindfulnessMedia.getMediaUrl();
                if (media!=null){
                    URL mediaUrl = new URL(media);
                    String mediaFileName = mediaUrl.getPath().substring(mediaUrl.getPath().lastIndexOf("/") + 1);
                    FileUtils.delete(mindfulnessMediaPath + mediaFileName);
                }
            }catch (Exception e){
                throw new RuntimeException("错误"+e);
            }

            row = mindfulnessMediaMapper.delete(mindfulnessMedia)+row;
        }

        return row;
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public int deleteList(Integer[] ids) {
        int row = 0;
        if (ids.length!=0){
            for (Integer id:ids) {
                MindfulnessMedia mindfulnessMedia = mindfulnessMediaMapper.selectById(id);
                if (mindfulnessMedia!=null){
                    Mindfulness mindfulness = new Mindfulness();
                    mindfulness.setId(id);
                    List<Mindfulness>  mindfulnessList = mindfulnessMapper.select(mindfulness);
                    // 删除实体关系
                    if (!mindfulnessList.isEmpty()){
                        for (Mindfulness res:mindfulnessList) {
                            row = mindfulnessMapper.delete(res)+row;
                        }
                    }
                    // 删除图片和正念媒体
                    try{
                        String img = mindfulnessMedia.getImgUrl();
                        if (img!=null){
                            URL imgUrl = new URL(img);
                            String imgFileName = imgUrl.getPath().substring(imgUrl.getPath().lastIndexOf("/") + 1);
                            FileUtils.delete(mindfulnessMediaImgPath + imgFileName);
                        }
                        String media = mindfulnessMedia.getMediaUrl();
                        if (media!=null){
                            URL mediaUrl = new URL(media);
                            String mediaFileName = mediaUrl.getPath().substring(mediaUrl.getPath().lastIndexOf("/") + 1);
                            FileUtils.delete(mindfulnessMediaPath + mediaFileName);
                        }
                    }catch (Exception e){
                        throw new RuntimeException("错误"+e);
                    }

                    row = mindfulnessMediaMapper.delete(mindfulnessMedia)+row;
                }
            }
        }
        return row;
    }

    /**
     * 更新
     *
     * @param media
     * @param image
     * @param mindfulnessMedia
     * @param mediaClass
     * @return
     */
    @Override
    @Transactional
    public int update(MultipartFile media, MultipartFile image,
                      MindfulnessMedia mindfulnessMedia, Integer[] mediaClass) {
        int row = 0;
        Integer mediaId = mindfulnessMedia.getId();
        Date date = new Date();
        MindfulnessMedia res = mindfulnessMediaMapper.selectById(mediaId);

        if(!image.isEmpty()){
            // 先尝试删除本地旧文件
            try{
                String img = res.getImgUrl();
                if (img!=null){
                    URL imgUrl = new URL(img);
                    String imgFileName = imgUrl.getPath().substring(imgUrl.getPath().lastIndexOf("/") + 1);
                    FileUtils.delete(mindfulnessMediaImgPath + imgFileName);
                }
            }catch (Exception e){
                throw new RuntimeException("错误"+e);
            }

            String ImgURL = FileUtils.uploadImage(image,mindfulnessMediaImgPath,mindfulnessMediaImgURL);
            mindfulnessMedia.setImgUrl(ImgURL);
        }
        if (!media.isEmpty()){
            // 先尝试删除本地旧文件
            try{
                String oldMedia = res.getMediaUrl();
                if (oldMedia!=null){
                    URL mediaUrl = new URL(oldMedia);
                    String mediaFileName = mediaUrl.getPath().substring(mediaUrl.getPath().lastIndexOf("/") + 1);
                    FileUtils.delete(mindfulnessMediaPath + mediaFileName);
                }
            }catch (Exception e){
                throw new RuntimeException("错误"+e);
            }
            String mindfulMediaURL = "";
            // 上传正念媒体文件
            if (FileUtils.isMusic(media)){
                mindfulMediaURL = FileUtils.uploadImage(media,mindfulnessMediaPath,mindfulnessAudioURL);
            } else if (FileUtils.isVideo((media))){
                mindfulMediaURL = FileUtils.uploadImage(media,mindfulnessMediaPath,mindfulnessMediaURL);
            }
            if (!mindfulMediaURL.equals("")){
                mindfulnessMedia.setMediaUrl(mindfulMediaURL);
            } else {
                return 0;
            }
        }
        // 如果存储正念类别的数组不为空
        if (mediaClass.length!=0){
            Mindfulness mind = new Mindfulness();
            mind.setMediaId(mediaId);
            mindfulnessMapper.delete(mind);    // 先删除旧的实体关联
            for (Integer classId:mediaClass) {
                Mindfulness mindfulness = new Mindfulness(null,classId,mediaId);
                mindfulnessMapper.insert(mindfulness);   // 新增正念类别实体关系
            }
        }
        mindfulnessMedia.setGmtCreate(date);
        mindfulnessMedia.setGmtModified(date);

        row = mindfulnessMediaMapper.update(mindfulnessMedia)+row;
        return row;
    }

    /**
     * 根据id查询具体信息
     *
     * @param id
     * @return
     */
    @Override
    public MindfulnessMedia selectById(Integer id) {
        return mindfulnessMediaMapper.selectById(id);
    }

    /**
     * 根据name查询
     *
     * @param mediaName
     * @return
     */
    @Override
    public List<MindfulnessMedia> likeSelect(String mediaName) {
        MindfulnessMedia mindfulnessMedia = new MindfulnessMedia();
        mindfulnessMedia.setMediaName(mediaName);
        return mindfulnessMediaMapper.likeSelect(mindfulnessMedia);
    }

    /**
     * 分页查询
     *
     * @param pageVo
     * @return
     */
    @Override
    public List<MindfulnessMedia> likeSelectPage(PageVo pageVo) {
        // 获取当前页数和每页显示的数据条数
        Integer pageNo = pageVo.getPageNo();
        Integer pageSize = pageVo.getPageSize();
        // 计算OFFSET值
        Integer offset = (pageNo - 1) * pageSize;
        String mediaName = pageVo.getMediaName();
        return mindfulnessMediaMapper.likeSelectPage(mediaName,offset,pageSize);
    }

    /**
     * 分页查询（根据用户id）
     *
     * @param pageVo
     * @return
     */
    @Override
    public List<MindfulnessMedia> selectByAuthor(PageVo pageVo) {
        // 获取当前页数和每页显示的数据条数
        Integer pageNo = pageVo.getPageNo();
        Integer pageSize = pageVo.getPageSize();
        // 计算OFFSET值
        Integer offset = (pageNo - 1) * pageSize;
        Integer author = pageVo.getUid();
        return mindfulnessMediaMapper.selectByAuthor(author,offset,pageSize);
    }

    /**
     * 分页查询 (管理端)
     *
     * @param pageVo
     * @return
     */
    @Override
    public List<MindfulnessMedia> likeSelectList(PageVo pageVo) {
        // 获取当前页数和每页显示的数据条数
        Integer pageNo = pageVo.getPageNo();
        Integer pageSize = pageVo.getPageSize();
        // 计算OFFSET值
        Integer offset = (pageNo - 1) * pageSize;
        return mindfulnessMediaMapper.likeSelectList(offset,pageSize);
    }
}
